import {onMounted, ref} from "vue";
import DEFAULT_CONFIG from "@/config/index.js";

export function createAgentAi(){
    //websocket
    let ws = ref({})
    const connected = ref(false)
    const loading = ref(false)
    const agentModel = ref("")

    const messages = ref([
        {role: 'assistant', content: '你好！我是AI助手,有什么可以帮你的吗?'}
    ])
    onMounted(()=>{
        ws.value=new WebSocket(DEFAULT_CONFIG.AI_URL)

        ws.value.onopen=()=>{
            console.log("websocket连接成功")
            connected.value = true
        }

        ws.value.onclose = (event) => {
            connected.value = false
        }

        ws.value.onmessage=receiveMessage;
    })

    //发送消息

    const sendMessage=(message)=>{
        if (ws.value && ws.value.readyState === WebSocket.OPEN) {

            if (agentModel.value!==''&& agentModel.value.length>5){
                let ms=[];
                const msg = {
                    role: 'user',
                    content: message
                }
                ms.push(msg);

                let obj = {
                    type: 'batchV3',
                    model: agentModel.value,
                    message: JSON.stringify(ms),
                }

                console.log(obj)
                ws.value.send(JSON.stringify(obj));
            }else{
                const msg = {
                    type: 'prompt',
                    message: message
                }
                ws.value.send(JSON.stringify(msg))
            }

        }
    }
    const isLastMessageAssistant = () => {
        return messages.value.length > 0 &&
            messages.value[messages.value.length - 1].role === 'assistant'
    }

// 辅助函数：检查最后一条消息是否是推理消息
    const isLastMessageReasoning = () => {
        return messages.value.length > 0 &&
            messages.value[messages.value.length - 1].role === 'reasoning'
    }
    //接收消息处理
    const receiveMessage=(event)=>{
        console.log("接收到消息："+event)
        let message = ''
        const msg = JSON.parse(event.data)

        if (msg.messageType === 'content' ) {
            if(msg.content===""){
                return;
            }
            if (isLastMessageAssistant()) {
                // 如果最后一条是助手消息，追加内容
                const lastMsg = messages.value[messages.value.length - 1]
                lastMsg.content += msg.content || ''
            } else {
                // 否则创建新的助手消息
                messages.value.push({
                    role: 'assistant',
                    content: msg.content || ''
                })
            }
        }
        else if (msg.messageType === 'reasoning') {
            if(msg.content===""){
                return;
            }
            if (isLastMessageReasoning()) {
                // 如果最后一条是助手消息，追加内容
                const lastMsg = messages.value[messages.value.length - 1]
                lastMsg.content += msg.content || ''
            } else {
                // 否则创建新的助手消息
                messages.value.push({
                    role: 'reasoning',
                    content: msg.content || ''
                })
            }
        }
        else if (msg.messageType === 'over') {
            loading.value = false
        }

    }

    return {
        ws,sendMessage,agentModel,connected,messages,loading
    }



}
